import { reactive, ref } from "vue";

import { ElMessage } from "element-plus";

import { apiList } from "@/api/apiList";

import * as turf from "@turf/turf";

import _ from "lodash";

function mixin(props) {

  let daorutufuparams = reactive({
    tufutext: '',
    fenfufangshi: 'guobiao',
    bilichival: '0',
    showtufuhao: false,
    zhidingdaxiaoval: 1000
  })

  let guobiaoradiooption = ref([
    { label: "1:500", value: "0", display: { min: 0, max: 3000 } },
    { label: "1:1000", value: "1", display: { min: 0, max: 7000 } },
    { label: "1:2000", value: "2", display: { min: 0, max: 15000 } },
    { label: "1:5000", value: "3", display: { min: 0, max: 30000 } },
    { label: "1:10000", value: "4", display: { min: 0, max: 60000 } },
    { label: "1:25000", value: "5", display: { min: 0, max: 150000 } },
    { label: "1:50000", value: "6", display: { min: 0, max: 200000 } },
    { label: "1:100000", value: "7", display: { min: 0, max: 400000 } },
    { label: "1:250000", value: "8", display: { min: 0, max: 1200000 } },
    { label: "1:500000", value: "9", display: { min: 0, max: 2000000 } },
    { label: "1:1000000", value: "10", display: { min: 0, max: 3200000 } },
  ]);

  function fenfuzhidingdaxiao() {

    if (props.fenfaparams.quyufanweival.length == 0) {
      ElMessage.success("输入范围不能为空")
      return
    }

    props.fenfaparams.quyufanweival.map(item => {

      let wgs84pos = item.features[0].geometry.coordinates[0];
      console.log(wgs84pos);
      let bbox = [wgs84pos[3][0], wgs84pos[3][1], wgs84pos[1][0], wgs84pos[1][1]];
  
      // var bbox = [-95, 30, -85, 40];
      var cellSide = daorutufuparams.zhidingdaxiaoval / 1000;
      var options = { units: "kilometers" };
      
      var squareGrid = turf.squareGrid(bbox, cellSide, options);

      addquyutomap([squareGrid])
  
    })


  }

  function addquyutomap(quyufanweival) {

    // 判断单个还是几多个多边形
    let fenfuitem = guobiaoradiooption.value.filter((item) => {
      return item.value == daorutufuparams.bilichival;
    })[0];

    quyufanweival.map((item1) => {
      item1.features.map((item) => {
        if (item.geometry.type == 'Polygon') {
          viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(
              (item.geometry.coordinates[0][0][0] +
                item.geometry.coordinates[0][2][0]) /
              2,
              (item.geometry.coordinates[0][0][1] +
                item.geometry.coordinates[0][1][1]) /
              2
            ),

            label: {
              text: _.has(item.properties, 'SheetName') ? item.properties.SheetName : '',
              // text: item.properties.ID + "\n" + item.properties.fanwei.split(" ").join("\n"),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                fenfuitem.display.min,
                fenfuitem.display.max
              ),
            },
            polyline: {
              // positions: new Cesium.CallbackProperty(function () {
              //   return Cesium.Cartesian3.fromDegreesArray(
              //     item.geometry.coordinates[0].flat()
              //   );
              // }, false),
              positions: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
              // hierarchy: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
              width: 3,
              material: Cesium.Color.YELLOW.withAlpha(0.5),
              // material: Cesium.Color.RED.withAlpha(0.5),
            },
          });
        } else {
          viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(
              (item.geometry.coordinates[0][0][0][0] +
                item.geometry.coordinates[0][0][2][0]) /
              2,
              (item.geometry.coordinates[0][0][0][1] +
                item.geometry.coordinates[0][0][1][1]) /
              2
            ),

            label: {
              text: _.has(item.properties, 'SheetName') ? item.properties.SheetName : '',
              // text: item.properties.ID + "\n" + item.properties.fanwei.split(" ").join("\n"),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                fenfuitem.display.min,
                fenfuitem.display.max
              ),
            },
            polyline: {
              positions: new Cesium.CallbackProperty(function () {
                return Cesium.Cartesian3.fromDegreesArray(
                  item.geometry.coordinates[0][0].flat()
                );
              }, false),
              // positions: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
              // hierarchy: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
              width: 3,
              material: Cesium.Color.YELLOW.withAlpha(0.5),
            },
          });
        }
      });
    });
  }


  function uploadTuFuFile(file) {
    let fileName = file.name;
    const reader = new FileReader();
    // 异步处理文件数据
    reader.readAsText(file.raw, "UTF-8");
    // 处理完成后立马触发 onload
    reader.onload = (fileReader) => {
      const fileData = fileReader.target.result;
      daorutufuparams.tufutext = fileData
    };
  }

  function uploadShiLiangFile(file) {
    let fileName = file.name;
    const reader = new FileReader();
    // 异步处理文件数据
    reader.readAsText(file.raw, "UTF-8");
    // 处理完成后立马触发 onload
    reader.onload = (fileReader) => {
      const fileData = fileReader.target.result;
      try {
        // 添加到地图
        // 添加到场景
        let resjson = JSON.parse(fileData)
        addquyutomap([resjson])
        props.fenfaparams.fenggefangshival = fileData
      } catch (error) {
        console.log(error);
        ElMessage.success("格式有错误" + error)
      }
    };
  }

  function tufuhao() {
    // 文件导入
    // 手动导入
    // 层级导入
    // 分幅方式导入
    // 地图回显

    if (daorutufuparams.tufutext == '') {
      ElMessage.success("图幅号不能为空")
      return
    }
    let params = {
      sheetsNum: [],
      "type": 0,
      // "type": daorutufuparams.fenfufangshi,
      "scale": daorutufuparams.bilichival
    }
`↵H48I105148`

daorutufuparams.tufutext.replace('\n', '')
daorutufuparams.tufutext.replace('\r', '')

    let resarr = []

    params.sheetsNum = daorutufuparams.tufutext.split(",").map(item => {
      if (item != '') {
        resarr.push(item)
      }
    })

    params.sheetsNum = resarr

    apiList.getFramingSheet(params).then((res) => {
      addquyutomap([res.data])
    });
  }


  // 本地方法 获取国标分幅
  function getresjson(ojson) {
    let wgs84pos = ojson.features[0].geometry.coordinates[0];
    let bbox = [wgs84pos[3][1], wgs84pos[1][1], wgs84pos[3][0], wgs84pos[1][0]];

    if (bbox[0] > bbox[1]) {
      bbox = [bbox[1], bbox[0], bbox[2], bbox[3]];
    }
    if (bbox[2] > bbox[3]) {
      bbox = [bbox[0], bbox[1], bbox[3], bbox[2]];
    }
    bbox = [bbox[2], bbox[0], bbox[3], bbox[1]];

    console.log(bbox);
    let resjson = makeStandardMapGrids(
      bbox[0],
      bbox[1],
      bbox[2],
      bbox[3],
      guobiaoval.value * 1
    );
    return resjson;
  }



  // 军标分幅 接口方式
  function fenfuguobiao1() {

    let params = {
      geojson: "",
      type: "",
      scale: guobiaoval.value,
    };

    let tmpjson = {
      type: "FeatureCollection",
      features: [],
    };



    if (props.fenfaparams.quyufanweival.length == 0) {
      ElMessage.success("输入范围不能为空")
      return
    }

    props.fenfaparams.quyufanweival.map((item) => {
      tmpjson.features.push(...item.features);
    });

    params.geojson = JSON.stringify(tmpjson);
    let fenfuitem = {};
    if (fengefangshitype.value == "国标") {
      params.type = "guobiao";
      params.scale = guobiaoval.value;
      fenfuitem = guobiaoradiooption.value.filter((item) => {
        return item.value == guobiaoval.value;
      })[0];
    } else {
      params.type = "junbiao";
      params.scale = junbiaoval.value;
      fenfuitem = junbiaoradiooption.value.filter((item) => {
        return item.value == junbiaoval.value;
      })[0];
    }

    apiList.getFramingMeans(params).then((res) => {
      // 获取数据
      // 赋值
      // 渲染样式

      res.data.features.map((item) => {
        viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            (item.geometry.coordinates[0][0][0][0] +
              item.geometry.coordinates[0][0][2][0]) /
            2,
            (item.geometry.coordinates[0][0][0][1] +
              item.geometry.coordinates[0][0][1][1]) /
            2
          ),

          label: {
            text: item.properties.SheetName,
            // text: item.properties.ID + "\n" + item.properties.fanwei.split(" ").join("\n"),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              fenfuitem.display.min,
              fenfuitem.display.max
            ),
          },
          polyline: {
            positions: new Cesium.CallbackProperty(function () {
              return Cesium.Cartesian3.fromDegreesArray(
                item.geometry.coordinates[0][0].flat()
              );
            }, false),
            // positions: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
            // hierarchy: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
            width: 3,
            material: Cesium.Color.YELLOW.withAlpha(0.5),
          },
        });
      });
    });
  }

  // 国标分幅 本地方式
  function fenfuguobiao() {
    let fenfuitem = guobiaoradiooption.value.filter((item) => {
      return item.value == guobiaoval.value;
    })[0];

    props.fenfaparams.quyufanweival.map((item1) => {
      // 格式化范围数据 并获取分幅之后数据
      let fenfujson = getresjson(item1);

      fenfujson.features.map((item) => {
        viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            (item.geometry.coordinates[0][0][0] + item.geometry.coordinates[0][1][0]) / 2,
            (item.geometry.coordinates[0][1][1] + item.geometry.coordinates[0][2][1]) / 2
          ),

          label: {
            text: item.properties.ID,
            // text: item.properties.ID + "\n" + item.properties.fanwei.split(" ").join("\n"),
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              fenfuitem.display.min,
              fenfuitem.display.max
            ),
          },
          polyline: {
            positions: new Cesium.CallbackProperty(function () {
              return Cesium.Cartesian3.fromDegreesArray(
                item.geometry.coordinates[0].flat()
              );
            }, false),
            // positions: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
            // hierarchy: Cesium.Cartesian3.fromDegreesArray(item.geometry.coordinates[0].flat()),
            width: 3,
            material: Cesium.Color.YELLOW.withAlpha(0.5),
          },
        });
      });
    });
  }

  return {
    uploadTuFuFile,
    uploadShiLiangFile,
    fenfuzhidingdaxiao,
    fenfuguobiao1,
    tufuhao,
    daorutufuparams,
  }
}

export default mixin